<?php

/**
 * PHP versions 4 and 5
 * MagicPHP
 * Licensed under The Open Group Test Suite License
 * Redistributions of files must retain the above copyright notice.
 * @copyright     Copyright 2011
 * @link
 * @package       Model
 * @since         MaginPHP 1.0
 * @license
 * @desc	here you have to mention query type .Types of query are followin
 */
?>
<?php

Magic::callMethod()->importLibarary("Magic_Paging_Model", "", $debug = false);

/**
 * @author:
 * @desc: this function is use for creating a paging
 * @param $pagingArray: this is paggin array contain following elements */
/* $pagingArray =array ("dbTableName" => 'name of table .if muliple table is come with comma seperation' ,
  "tableDisplayField" => is array of database field that you want to display in table ,
  "tableDisplayFieldTitle" =>titile of field that you want to display in table,
  "databaseFetchField" => fields that you want to fetch from database . If table is muliple
  tant field is come with  tablename.field ,
  "pageName"=>"name of page",
  "extraCondition"=> "",
  "recordPerPage"=> total number of record per page,
  "noOfLink"=>"number of link per page",
  "joinStatus"=>"if table is multiple than 1 else status 0" ,
  "queryType"=>type of query ,
  "whereCondition"=> " condition of query " ,
  "leftJoinStatus"=>"if query  having left join than 1 otherwise 1",
  "activeStatus"=>" for display of active button 1 other wise 0",
  "deleteStatus"=>"for display of delete button 1 other wise 0",
  "editStatus"=> "for display of edit button 1 other wise 0"
  "primarykeyFieldName"=>name of table primarykey);
 */
class Magic_CreatePagin_Model extends Magic_Paging_Model {
    /*
     * @return string: string of tables
     */

    public function createPaging($pagingArray) {
        //echo "<pre>";print_r($pagingArray); die
        if (array_key_exists('extraColumnStatus', $pagingArray) && $pagingArray["extraColumnStatus"] == 1) {
            $resultNewArray = $this->pushExtraColumn($pagingArray["extraColumnArray"], $pagingArray["tableDisplayField"], $pagingArray["tableDisplayFieldTitle"]);
            $tableDisplayField = $resultNewArray["field"];

            $tableDisplayFieldTitle = $resultNewArray["title"];
            $extraColumnField = $resultNewArray["extraColumnField"];
            $extraTitle = $resultNewArray["extraTitle"];
        } else {
            $tableDisplayField = $pagingArray["tableDisplayField"];
            $tableDisplayFieldTitle = $pagingArray["tableDisplayFieldTitle"];
        }
        //echo "<pre>";print_r($extraTitle);
        $databaseFetchField = $pagingArray["databaseFetchField"];
        $previous_start = 0;
        $start = 0;
        /* ------------- Set Start here -------------------------------------- */
        if (isset($_REQUEST["start"]) && isset($_REQUEST["start"])) {
            $start = $_REQUEST["start"];
        }
        /* ------------------------- End -------------------------------------- */

        /* ---------------Set Order By ---------------------------------------- */
        $Order = $this->setOrder(@$_REQUEST["order"], @$_REQUEST["sortorder"], $start);
        $search = '';
        $idsandorder = $this->createOrderAndIds($pagingArray["joinStatus"], $pagingArray["dbTableName"], $pagingArray["primarykeyFieldName"]);

        $OrderBy = $idsandorder["orderby"];
        $w_id = $idsandorder["w_id"];
        /* ------------------------- End -------------------------------------- */
        $sea = '<tr><th></th>';
        $idsarray = array();
        $img = '';
        $keyval = '';
        $querytype = $pagingArray["queryType"];

        /* -------------      End       -------------------------------------- */
        /* ------------- Set OrderBy here -------------------------------------- */
        if ($pagingArray["joinStatus"] == 1) {
            $firstTable = explode(",", $pagingArray["dbTableName"]);
            if (@$_REQUEST["orderby"] == '') {
                //$OrderBy=$OrderBy .$firstTable[0].".".$pagingArray["primarykeyFieldName"];
                $OrderBy = $OrderBy;
            } else {
                $OrderBy = 'ORDER BY ' . @$_REQUEST["orderby"];
            }
        } else {
            if (@$_REQUEST["orderby"] == '') {
                $OrderBy = $OrderBy;
            } else {
                $OrderBy = 'ORDER BY ' . @$_REQUEST["orderby"];
            }
        }
        /* -------------       End        -------------------------------------- */

        /* ----------------print Query ----------------------------------------- */
        $extraCondition = $this->multiSearchCondition(@$_POST, $pagingArray["joinStatus"], $pagingArray["dbTableName"], $tableDisplayField);
        $sql = $this->queryGenerator($pagingArray["dbTableName"], $pagingArray["databaseFetchField"], $pagingArray["beforeWhereCondition"], $pagingArray["afterWhereCondition"], $pagingArray["joinStatus"], @$_REQUEST["key"], @$_REQUEST["keyword"], $OrderBy, $Order, $search, @$_REQUEST["date1"], @$_REQUEST["date2"], $pagingArray["primarykeyFieldName"], $extraCondition);
        @$_SESSION["sql"] = $sql;
        if (array_key_exists('debugQuery', $pagingArray)) {
            if ($pagingArray["debugQuery"] == 1) {
                echo $sql;
            }
        }
        /* -------------       End        -------------------------------------- */
        $ext = '';
        $extraUrlPara = '';

        $extra = '&sortorder=1';
        if (array_key_exists('extraUrlPara', $pagingArray)) {
            $extraUrlPara = "&" . $pagingArray["extraUrlPara"];
        } else {
            $extraUrlPara = "";
        }

        $thispage = $pagingArray["pageName"] . "?keyword=" . @$_REQUEST["keyword"] . "&key=" . @$_REQUEST["key"] . "&orderby=" . @$w_id . "&order=" . $Order . "&numofrecord=" . $pagingArray["recordPerPage"] . "&date1=" . @$_REQUEST["date1"] . "&date2=" . @$_REQUEST["date2"] . "&interval=" . @$_REQUEST["interval"] . $extraUrlPara;
        if (@$_REQUEST["start"] != '') {
            $start = $_REQUEST["start"];
            $k = $start;
        } else {
            $start = 0;
            $k = 1;
        }

        $ids = $this->toralRecordSet($sql, $w_id);
        $total_record = count($ids);

        if (($total_record - $start) > 0) {
            $end = min(($total_record - $start), $pagingArray["recordPerPage"]);
        } else {
            $start = 0;
            $end = min($pagingArray["recordPerPage"], $total_record);
        }
        $limitString = "&& " . $pagingArray["primarykeyFieldName"] . " IN (" . $this->getWhereID($start, $end, $ids, $pagingArray["recordPerPage"], $total_record) . " )";
        $record_paging = $this->queryGenerator($pagingArray["dbTableName"], $pagingArray["databaseFetchField"], $pagingArray["beforeWhereCondition"], $pagingArray["afterWhereCondition"], $pagingArray["joinStatus"], @$_REQUEST["key"], @$_REQUEST["keyword"], $OrderBy, $Order, $search, @$_REQUEST["date1"], @$_REQUEST["date2"], $pagingArray["primarykeyFieldName"], $extraCondition, $limitString);
        $table = '<table id="chart_table"  width="500" cellspacing="0" cellpadding="0" border="0"><tr><th scope="col" valign="top"><input type="checkbox" onClick="checkAll(document.myform.chk);" /></th>';
        $Index = array_search(@$_REQUEST["orderby"], $tableDisplayField);
        $searchPanel = '<tr><td>#</td>';
        for ($i = 0; $i < count($tableDisplayFieldTitle); $i++) {

            $sea.='<th valign="top"><input type="text" value="' . $tableDisplayFieldTitle[$i] . '" name="' . $tableDisplayFieldTitle[$i] . '" /></th> ';
            if ($Index > -1) {
                if ($Index == $i) {
                    if ($Order == 'ASC') {
                        $img = "^";
                    } else {
                        $img = "v";
                    }
                    // $img = '<img border="0" src="../public/images/' . $Order . '.png">';
                } else {
                    $img = '';
                }
            }
            if (array_key_exists('extraColumnStatus', $pagingArray) && $pagingArray["extraColumnStatus"] == 1) {
                if (in_array($tableDisplayFieldTitle[$i], $extraTitle)) {

                    $table.='<th scope="col" valign="top">
                                <a style="cursor:crosshair ;text-decorate:none;color:green;font-weight:normal" href="#">
                                    ' . $tableDisplayFieldTitle[$i] .
                            '<a>
                            </th>';
                    $searchPanel .= "<td>#</td>";
                } else {
                    $table.='<th scope="col" valign="top">
			     <a style="text-decorate:none;color:#000;font-weight:normal" 	
                             href="' . $pagingArray["pageName"] . '?key=' . $tableDisplayField[$i] . '&sortorder=' . @$_REQUEST["sortorder"] . '&keyword=' . @$_REQUEST["keyword"] . '&orderby=' . $tableDisplayField[$i] . '&order=' . $Order . '&numofrecord=' . $pagingArray["recordPerPage"] . '&start=' . $start . $extraUrlPara . '">' . @$tableDisplayFieldTitle[$i] . '</a>&nbsp;&nbsp;' . $img . '</th>';
                    $searchPanel .= '<td><input size ="10" type="textbox" value="' . @$_POST[$tableDisplayField[$i]] . '" name="' . $tableDisplayField[$i] . '" /></td>';
                }
            } else {
                $table.='<th scope="col" valign="top">
						<a style="text-decorate:none;color:#000;font-weight:normal" 	href="' . $pagingArray["pageName"] . '?key=' . $tableDisplayField[$i] . '&sortorder=' . @$_REQUEST["sortorder"] . '&keyword=' . @$_REQUEST["keyword"] . '&orderby=' . $tableDisplayField[$i] . '&order=' . $Order . '&numofrecord=' . $pagingArray["recordPerPage"] . '&start=' . $start . $extraUrlPara . '">' . @$tableDisplayFieldTitle[$i] . '</a>&nbsp;&nbsp;' . $img . '</th>';
                $searchPanel .= '<td><input type="textbox" name="' . $tableDisplayField[$i] . '" value="' . @$_POST[$tableDisplayField[$i]] . '" size ="10" /></td>';
            }
        }

        $table.='<th scope="col" valign="top" style="text-decorate:none;color:#000;font-weight:normal" >Action</th></tr>';
        $searchPanel .= '<td></td></tr>';

        $table .= $searchPanel;
        $num = @mysql_num_rows($record_paging);
        if ($num > 0) {
            while ($data = @mysql_fetch_assoc($record_paging)) {
                if ($pagingArray["joinStatus"] == 1) {
                    $tabs = explode(",", $pagingArray["dbTableName"]);
                    $tab = $tabs[0];
                } else {
                    $tab = $pagingArray["dbTableName"];
                }

                $k % 2 == 0 ? $bg = "td" : $bg = "nexttd";
                $table.='<tr><td valign="top" class="' . $bg . '" width="30" align="left"><input type="checkbox" name="chk[]" id="chk"  class="chk_' . $data[$pagingArray["primarykeyFieldName"]] . '" value="' . $data[$pagingArray["primarykeyFieldName"]] . '"/></td>';
                for ($j = 0; $j < count($tableDisplayField); $j++) { //START
                    if (array_key_exists('extraColumnStatus', $pagingArray) && $pagingArray["extraColumnStatus"] == 1) {
                        if (in_array($tableDisplayField[$j], $extraColumnField)) {
                            $mResult = Magic_Common_Model::inMultiDimentionArray($tableDisplayField[$j], $pagingArray["extraColumnArray"]);
                            $evalStr = $pagingArray["extraColumnArray"][$mResult["position"]]["cDisplayValue"];
                            $table.='<td valign="top" class="' . $bg . '">' . $this->magicEval($evalStr) . '</td>';
                            $displayVal = '';
                        } else {
                            $table.='<td valign="top" class="' . $bg . '">' . @$data[$tableDisplayField[$j]] . '</td>';
                        }
                    } else {
                        $table.='<td valign="top" class="' . $bg . '">' . @$data[$tableDisplayField[$j]] . '</td>';
                    }
                } // END

                $table.='<td valign="top" class="' . $bg . '" width="150">';

                if ($pagingArray["activeStatus"] == 0) {
                    if ($data["is_active"] == 0) {
                        $table.='<a href="#" title="Active" onclick="makeActiveInactiveDelete(' . $data[$pagingArray["primarykeyFieldName"]] . ',1,' . $start . ',\'' . $pagingArray["primarykeyFieldName"] . '\');" class="active_button">Active</a>';
                    } else {
                        $table.='<a href="#" title="Deactive" onclick="makeActiveInactiveDelete(' . $data[$pagingArray["primarykeyFieldName"]] . ',2,' . $start . ',\'' . $pagingArray["primarykeyFieldName"] . '\');" class="deactive_button">Inactive</a>';
                    }
                }
                $insert_page = explode('_', $pagingArray["pageName"]);
                if ($pagingArray["deleteStatus"] == 0) {
                    $table.='<a href="#" title="Delete" onclick="makeActiveInactiveDelete(' . $data[$pagingArray["primarykeyFieldName"]] . ',3,' . $start . ',\'' . $pagingArray["primarykeyFieldName"] . '\');" class="delete_button">Delete</a>';
                }
                if ($pagingArray["editStatus"] == 0) {
                    $table.='<a href="' . $insert_page[0] . '_insert_update?id=' . $data[$pagingArray["primarykeyFieldName"]] . '&start=' . @$_REQUEST["start"] . '" title="Edit" class="edit_button">Edit</a>';
                }
                if (array_key_exists('extraLink', $pagingArray)) {

                    $extraLink = $this->magicEval($pagingArray["extraLink"]);
                    $table.= $extraLink;
                }
                $table.='</td></tr>';
                $k++;
            }
            $table.="</table><div id='total'><em>Total Records :</em><b> " . $total_record . "</b></div>";
            $table.="<div id='pagingNos'>" . $this->previousLink($thispage, $start, $total_record, $pagingArray["recordPerPage"], $extra);
            $table.= $this->middleLink($total_record, $thispage, $start, $pagingArray["recordPerPage"], $pagingArray["noOfLink"], $extra);
            $table.= $this->nextLink($thispage, $start, $total_record, $pagingArray["recordPerPage"], $extra);
            $table.='</div>';
            return $table;
        } else if (isset($_REQUEST["key"]) && $_REQUEST["key"] != '' && $num == '0') {
            return '<div align="center"><h1>Sorry Your Serach has no result ! Please Try Again !</h1></div>';
        } else {
            return '<div align="center"><h1>No Data.Please Insert Data.</h1></div>';
        }
        Magic_CURD_Model::callMethod()->magicFreeResult();
    }

// End Of Function
}

?>